﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.UI;
using JQuery.WebKit.Base;
using JQuery.WebKit.WebCommon;

namespace JQuery.WebKit
{
    [ParseChildren(typeof(JTabItem), DefaultProperty = "TabItems", ChildrenAsProperties = true)]
    public class JTab : WebControlBase
    {
        [PersistenceMode(PersistenceMode.InnerProperty),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public List<JTabItem> TabItems
        {
            get;
            private set;
        }

        public JTab()
            : base("div")
        {
            TabItems = new List<JTabItem>();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            EnsureChildControls();
        }

        protected override void OnPreRender(EventArgs e)
        {
            string script = string.Format("$('#{0}').tabs();", this.ClientID);
            this.Page.Resources.Add(new WebScriptResource(typeof(JTab), this.ClientID, ResourceType.Javascript, script, LoadEvent.NA));
            base.OnPreRender(e);
        }

        protected override void CreateChildControls()
        {
            foreach (JTabItem item in TabItems)
            {
                item.InstantiateIn(this);
                this.Controls.Add(item);
            }
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.Write("<ul>");
            foreach (JTabItem item in TabItems)
            {
                writer.WriteLine(string.Format("<li title=\"{2}\"><a href='#{0}'>{1}</a></li>", item.ClientID, item.Text, item.TooltipText));
            }
            writer.Write("</ul>");
            base.RenderContents(writer);
        }
    }
}
